import { localStorageInstance } from './store-instance';

type UserInfo = { name: string; age: number; token?: string };

interface LocalStorageData {
  userInfo: UserInfo | null
  token: string
  lang: string
}

const getDefaultValue = <K extends keyof LocalStorageData>(key: K) => {
  const defaultValueMap: Partial<LocalStorageData> = {
    lang: 'zh',
  };

  const defaultValue = defaultValueMap[key] !== undefined ? defaultValueMap[key] : null;

  return defaultValue as LocalStorageData[K];
};

export const localStorageUtil = {
  get: <K extends keyof LocalStorageData>(key: K): LocalStorageData[K] => localStorageInstance.get(key) ?? getDefaultValue(key),

  set: <K extends keyof LocalStorageData>(key: K, value: LocalStorageData[K]) => {
    localStorageInstance.set(key, value);
  },

  remove: (key: string) => {
    localStorageInstance.remove(key);
  },
};
